import React, { useState, useEffect, useRef } from 'react';
import { View, StyleSheet, TouchableOpacity, TextInput, FlatList, Image, Text, Button, Alert } from 'react-native';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import { useNavigation } from '@react-navigation/native';
import { useRoute } from '@react-navigation/native';
import { useAppSelector } from '../../../redux';
import { initSocket } from '../../../services/socket';
import api from '../../../api';

interface User {
    _id: string;
    username: string;
    avatar: string;
    uid: string;
}

const ZTsearch = () => {
    const [searchText, setSearchText] = useState('');
    const [searchResults, setSearchResults] = useState<User[]>([]);
    const [loading, setLoading] = useState(false);
    const [sendingRequests, setSendingRequests] = useState<{ [key: string]: boolean }>({});
    const [isConnecting, setIsConnecting] = useState(false);
    const socketRef = useRef<WebSocket | null>(null);
    
    const navigation = useNavigation();
    const route = useRoute();
    const { userInfo } = useAppSelector(state => state.auth);

    // 初始化WebSocket连接
    const initializeWebSocket = () => {
        if (!userInfo?._id || isConnecting) return;

        setIsConnecting(true);
        try {
            const ws = initSocket(userInfo._id);
            socketRef.current = ws;

            ws.onopen = () => {
                console.log('WebSocket连接已建立');
                setIsConnecting(false);
            };

            ws.onerror = (error) => {
                console.error('WebSocket连接错误:', error);
                setIsConnecting(false);
                Alert.alert('错误', 'WebSocket连接失败，请重试');
            };

            ws.onclose = () => {
                console.log('WebSocket连接已关闭');
                setIsConnecting(false);
                socketRef.current = null;
            };
        } catch (error) {
            console.error('初始化WebSocket失败:', error);
            setIsConnecting(false);
            Alert.alert('错误', '连接服务器失败，请重试');
        }
    };

    // 在组件挂载和userInfo变化时初始化WebSocket
    useEffect(() => {
        if (userInfo?._id) {
            initializeWebSocket();
        }
        return () => {
            if (socketRef.current) {
                socketRef.current.close();
                socketRef.current = null;
            }
        };
    }, [userInfo]);

    useEffect(() => {
        if (route.params && (route.params as any).searchText) {
            setSearchText((route.params as any).searchText);
            handleSearch((route.params as any).searchText);
        }
    }, [route.params]);

    const handleSearch = async (text: string) => {
        if (!text.trim()) {
            setSearchResults([]);
            return;
        }

        setLoading(true);
        try {
            const response = await api.get(`/zt/users/search?username=${text}`);
            if (response.data.status === 200) {
                // 过滤掉当前用户
                const filteredResults = response.data.data.filter(
                    (user: User) => user._id !== userInfo?._id
                );
                setSearchResults(filteredResults);
            }
        } catch (error) {
            console.error('搜索用户失败:', error);
            Alert.alert('错误', '搜索用户失败，请稍后重试');
        } finally {
            setLoading(false);
        }
    };

    const handleAddFriend = async (targetUser: User) => {
        if (!userInfo) {
            Alert.alert('提示', '请先登录');
            return;
        }

        if (sendingRequests[targetUser._id]) {
            return; // 防止重复发送
        }

        setSendingRequests(prev => ({ ...prev, [targetUser._id]: true }));

        try {
            const socket = initSocket(userInfo._id);
            const message = JSON.stringify({
                type: 'friendRequest',
                senderId: userInfo._id,
                receiverId: targetUser._id,
                content: `${userInfo.username}请求添加您为好友`,
                timestamp: Date.now(),
                status: 'pending'
            });

            if (socket.readyState === WebSocket.OPEN) {
                socket.send(message);
                Alert.alert('提示', '好友请求已发送');
            } else {
                throw new Error('WebSocket连接未建立');
            }
        } catch (error) {
            console.error('发送好友请求失败:', error);
            Alert.alert('错误', '发送好友请求失败，请稍后重试');
        } finally {
            // 3秒后重置发送状态
            setTimeout(() => {
                setSendingRequests(prev => ({ ...prev, [targetUser._id]: false }));
            }, 3000);
        }
    };

    return (
        <View style={styles.container}>
            <View style={styles.header}>
                <TouchableOpacity 
                    style={styles.backButton}
                    onPress={() => navigation.goBack()}
                >
                    <MaterialIcons name="arrow-back" size={24} color="#333" />
                </TouchableOpacity>
                <View style={styles.searchContainer}>
                    <MaterialIcons name="search" size={24} color="#888" style={styles.searchIcon} />
                    <TextInput
                        style={styles.searchInput}
                        placeholder="搜索用户名或ID"
                        placeholderTextColor="#888"
                        value={searchText}
                        onChangeText={setSearchText}
                        onSubmitEditing={() => handleSearch(searchText)}
                        returnKeyType="search"
                    />
                    {searchText ? (
                        <TouchableOpacity onPress={() => {
                            setSearchText('');
                            setSearchResults([]);
                        }}>
                            <MaterialIcons name="close" size={24} color="#888" />
                        </TouchableOpacity>
                    ) : null}
                </View>
            </View>

            {loading ? (
                <View style={styles.centerContent}>
                    <Text>搜索中...</Text>
                </View>
            ) : searchResults.length === 0 ? (
                <View style={styles.centerContent}>
                    <Text style={styles.noResultText}>
                        {searchText ? '未找到相关用户' : '请输入搜索关键词'}
                    </Text>
                </View>
            ) : (
                <FlatList
                    data={searchResults}
                    keyExtractor={item => item._id}
                    renderItem={({ item }) => (
                        <View style={styles.userItem}>
                            <Image 
                                source={{ uri: item.avatar || 'https://via.placeholder.com/50' }}
                                style={styles.avatar}
                            />
                            <View style={styles.userInfo}>
                                <Text style={styles.username}>{item.username}</Text>
                                <Text style={styles.userId}>ID: {item.uid}</Text>
                            </View>
                            <TouchableOpacity
                                style={[
                                    styles.addButton,
                                    sendingRequests[item._id] && styles.addButtonDisabled
                                ]}
                                onPress={() => handleAddFriend(item)}
                                disabled={sendingRequests[item._id]}
                            >
                                <Text style={styles.addButtonText}>
                                    {sendingRequests[item._id] ? '已发送' : '添加'}
                                </Text>
                            </TouchableOpacity>
                        </View>
                    )}
                    contentContainerStyle={styles.listContainer}
                />
            )}
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f5f5f5',
    },
    header: {
        flexDirection: 'row',
        alignItems: 'center',
        padding: 16,
        backgroundColor: '#fff',
    },
    backButton: {
        marginRight: 12,
    },
    searchContainer: {
        flex: 1,
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: '#f0f0f0',
        borderRadius: 20,
        paddingHorizontal: 12,
        paddingVertical: 8,
    },
    searchIcon: {
        marginRight: 8,
    },
    searchInput: {
        flex: 1,
        fontSize: 16,
        color: '#333',
        padding: 0,
    },
    centerContent: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    noResultText: {
        color: '#666',
        fontSize: 16,
    },
    listContainer: {
        padding: 16,
    },
    userItem: {
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: '#fff',
        padding: 12,
        borderRadius: 12,
        marginBottom: 8,
        elevation: 2,
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 1 },
        shadowOpacity: 0.2,
        shadowRadius: 2,
    },
    avatar: {
        width: 50,
        height: 50,
        borderRadius: 25,
    },
    userInfo: {
        flex: 1,
        marginLeft: 12,
    },
    username: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#333',
    },
    userId: {
        fontSize: 14,
        color: '#666',
        marginTop: 4,
    },
    addButton: {
        backgroundColor: '#4A90E2',
        paddingHorizontal: 16,
        paddingVertical: 8,
        borderRadius: 20,
    },
    addButtonDisabled: {
        backgroundColor: '#ccc',
    },
    addButtonText: {
        color: '#fff',
        fontSize: 14,
        fontWeight: 'bold',
    },
});

export default ZTsearch;